/**
 * SEVAS - Swiss Electronic Vaccination Advisor Service / Agile Development
 *
 * $Id: Controller.java 77 2010-09-19 19:31:48Z zimmr7@bfh.ch $
 */
package ch.bfh.sevas;

import ch.bfh.sevas.exceptions.NonexistentEntityException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

public class Controller {

    private EntityManagerFactory emf = null;
    private User user = null;

    public Controller() {
        emf = Persistence.createEntityManagerFactory("PersistenceUnit");
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public User getUser() {
        return user;
    }

    public void create(Patient patient) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(patient);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Patient patient) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            patient = em.merge(patient);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = patient.getId();
                if (findPatientById(id) == null) {
                    throw new NonexistentEntityException("The patient with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Patient patient;
            try {
                patient = em.getReference(Patient.class, id);
                patient.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The patient with id " + id + " no longer exists.", enfe);
            }
            em.remove(patient);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Patient> findAllPatients() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Patient.class));
            Query q = em.createQuery(cq);
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Patient findPatientById(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Patient.class, id);
        } finally {
            em.close();
        }
    }

    public List<Patient> findPatientsByAttributes(Map<String, String> attributes) {
        EntityManager em = getEntityManager();
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Patient> cq = cb.createQuery(Patient.class);
            Root<Patient> root = cq.from(Patient.class);

            List<Predicate> predicates = new ArrayList<Predicate>();
            for (String s : attributes.keySet()) {
                if (root.get(s) != null) {
                    predicates.add(cb.like((Expression) root.get(s), "%" + attributes.get(s) + "%"));
                }
            }
            cq.where(predicates.toArray(new Predicate[]{}));
            TypedQuery<Patient> q = em.createQuery(cq);

            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public int getPatientCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Patient> rt = cq.from(Patient.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public Vaccination addVaccinationFromTemplate(Patient patient, RecommendedBaseVaccination recommendation,
            String batchNo, String note, String dose, String age) {
        Vaccination vaccination = new Vaccination(recommendation.getAntigen(), recommendation.getVaccine(),
                recommendation.getManufacturer(), batchNo, dose, new Date(), user.getSignature(), note, recommendation.getCode(), age);
        patient.addVaccination(vaccination);
        return vaccination;
    }

    public User validateUserAuthentication(String loginName, String password) {
        if (loginName.equals(password)) {
            user = new User(loginName, password, "Dr. Beat Vogt (GLN 7603000157320)");
        } else user = null;
        return user;
    }

    void cleanup() {
        if (emf != null) {
            emf.close();
        }
    }
}
